# app/routers/goods_router.py
from typing import List, Optional
import logging
from fastapi import APIRouter, HTTPException, Path, Query
from app.schemas.goods_schemas import (
    GoodsCreate, 
    GoodsUpdate, 
    GoodsResponse
)
from app.services.goods_service import GoodsService

logger = logging.getLogger(__name__)
router = APIRouter()

@router.post("/", response_model=GoodsResponse, status_code=201)
async def create_goods(goods: GoodsCreate):
    """创建新商品"""
    try:
        logger.info(f"接收创建商品请求: {goods.model_dump()}")
        result = await GoodsService.create_goods(goods)
        logger.info(f"商品创建成功: goods_id={result.id}")
        return result
    except ValueError as e:
        logger.error(f"创建商品失败(商品编码重复): {str(e)}")
        raise HTTPException(
            status_code=409,  # 使用409 Conflict更适合表示资源冲突
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"创建商品失败(未知错误): {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/{goods_id}", response_model=GoodsResponse)
async def get_goods(goods_id: int = Path(..., title="商品ID", gt=0)):
    """获取单个商品信息"""
    try:
        logger.info(f"获取商品信息: goods_id={goods_id}")
        goods = await GoodsService.get_goods(goods_id)
        if not goods:
            logger.warning(f"商品不存在: goods_id={goods_id}")
            raise HTTPException(status_code=404, detail="Goods not found")
        logger.debug(f"成功获取商品信息: goods_id={goods_id}")
        return goods
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取商品信息失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")

@router.get("/", response_model=List[GoodsResponse])
async def list_goods(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的记录数"),
    category: Optional[str] = Query(None, description="商品类别")
):
    """获取商品列表"""
    try:
        logger.info(
            f"获取商品列表: skip={skip}, limit={limit}, category={category}"
        )
        goods_list = await GoodsService.list_goods(skip, limit, category)
        logger.debug(f"成功获取商品列表: count={len(goods_list)}")
        return goods_list
    except Exception as e:
        logger.error(f"获取商品列表失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail="Internal server error")
    
